package com.zhuangjie.rider.mq.consumer.listener.delay;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhuangjie.rabbit.listen.wrap.MQListener;
import com.zhuangjie.rider.entity.DeliveryOrder;
import com.zhuangjie.rider.enums.AssignState;
import com.zhuangjie.rider.enums.DeliveryOrderState;
import com.zhuangjie.rider.lock.DeliveryOrderLock;
import com.zhuangjie.rider.mq.producer.structure.DeliveryOrderMQStructure;
import com.zhuangjie.rider.service.DeliveryOrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class OrderCancelDelayMQListener extends MQListener<Long> {
    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private Redisson redisson;

    @Override
    public String listenQueue() {
        return DeliveryOrderMQStructure.Queues.CANCEL_ORDER_LOCK_QUEUE;
    }

    @Override
    public void onMessageArrives(Long deliveryOrderId) throws ClassNotFoundException {
        RLock lock = redisson.getLock(DeliveryOrderLock.getDeliveryOrderOperationLock(deliveryOrderId));
        lock.lock();
        try {
            LambdaUpdateWrapper<DeliveryOrder> updateAssignStateWrapper = Wrappers.lambdaUpdate(DeliveryOrder.class)
                    .eq(DeliveryOrder::getId, deliveryOrderId)
                    .eq(DeliveryOrder::getDeliveryState, DeliveryOrderState.PENDING_PICKUP.getValue())
                    .isNotNull(DeliveryOrder::getAssignRiderId)
                    .set(DeliveryOrder::getAssignRiderId, AssignState.UNASSIGNED);
            deliveryOrderService.update(updateAssignStateWrapper);
        }finally {
            lock.unlock();
        }
    }
}
